//
//  GameAudio.m
//  ImageAnimation
//
//  Created by apple on 5/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GameAudio.h"
#import <AVFoundation/AVFoundation.h>


@implementation GameAudio{
    AVAudioPlayer *backgroundMusicPlayer;
    AVAudioPlayer *dragAudioPlayer;
}

- (void)playBackgroundMusic{
    NSArray *musicsInApp = [[NSBundle mainBundle] pathsForResourcesOfType:@"mp3" inDirectory:nil];
    int index = arc4random()%musicsInApp.count;
    NSString *musicFilePath = [musicsInApp objectAtIndex:index];       //创建音乐文件路径
    NSData *sound1 = [NSData dataWithContentsOfFile:musicFilePath];
    
    //NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
    
    NSError *error = nil;
    backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithData:sound1 error:&error];
    
    [backgroundMusicPlayer prepareToPlay];
    [backgroundMusicPlayer play];
    
    [backgroundMusicPlayer setVolume:0.1];            //设置音量大小
    
    backgroundMusicPlayer.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环
}

- (void)playDragAudio{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"dragMusic" ofType:@"wav"];

    NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:path];
    
    dragAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
    
    [dragAudioPlayer play];
    
    dragAudioPlayer.numberOfLoops = 1;//设置音乐播放次数  -1为一直循环
}

+ (void)playBackgroundMusic1 
{

	
	NSData *sound1 = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"background1.mp3"]];
	NSData *sound2 = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"background2.mp3"]];
	
	NSOperationQueue *queue = [[NSOperationQueue alloc] init];
	NSError *error = nil;
	
	AVAudioPlayer *player1 = [[AVAudioPlayer alloc] initWithData:sound1 error:&error];
	AVAudioPlayer *player2 = [[AVAudioPlayer alloc] initWithData:sound2 error:&error];
	
	NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(playSounds:) object:player1];

	NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(playSounds:) object:player2];
	
	[queue addOperation:op1];
	[queue addOperation:op2];
	
}

+ (void)playSounds:(id)data
{
    AVAudioPlayer *player = (AVAudioPlayer *)data;
	
    [player prepareToPlay];
    [player play];
}
@end
